#!/bin/bash

if [[ $1 == "start" ]];then
for i in {1..4};do
docker run  -d -it --name "slave-$i" -p "800$i:54321"  rb/v1  /tmp/mutask/target/release/mmp -s "0.0.0.0:54321"
done
echo "start master"
docker run  -d -it --name "master" -p "54321:54321"  rb/v1  /tmp/mutask/target/release/mmp -s "0.0.0.0:54321"
elif [[ $1 == "compile" ]];then
   echo "ready files"
   if [ !  -d /tmp/mmp ];then
      mkdir /tmp/mutask;
   fi
   if [ ! -d /tmp/net-brd ];then
      mkdir /tmp/net-brd;
   fi
   cp Cargo.toml /tmp/mutask/;
   cp ../net-brd/Cargo.toml /tmp/net-brd/;
   cp -a src /tmp/mutask/;
   cp -a ../net-brd/src /tmp/net-brd/;
   cat << EOF >> /tmp/compile.sh
#!/bin/sh
cd /tmp/mutask;
cargo build --release
EOF
   chmod +x /tmp/compile.sh
   echo "start compile to linux"
docker run  -v /tmp:/tmp   rb/v1  "/tmp/compile.sh"
   echo "replace runner"
docker run -d -it --name rust rb/v1  bash
docker cp /tmp/mutask/target/release/mmp rust:/tmp/mutask/target/release/ ;
   echo "rebuild rb/v1"
docker commit rust rb/v1;
   echo "clean debug"
docker rm -f rust;
docker ps -a | grep "compile.sh" | awk '{print $1}'| xargs docker rm -f ;
elif [[ $1 == "stop" ]];then
docker ps -a | grep rb | awk '{print $1} ' |  xargs docker rm -f ;
fi
